package com.aerotechnic.dao.implementation;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.aerotechnic.dao.interfaces.MacroTacheDaoIn;
import com.aerotechnic.entities.JobCard;
import com.aerotechnic.entities.MacroTache;

@Repository("MacroTacheDao")
public class MacroTacheDao implements MacroTacheDaoIn {

	@Autowired
	private SessionFactory sessionFactory;

	private Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}

	@Override
	public void save(MacroTache t) {

		// TODO Auto-generated method stub

		getCurrentSession().save(t);

	}

	@Override
	public void delete(Long id) {
		// TODO Auto-generated method stub

		MacroTache e = findByID(id);
		if (e != null)
			getCurrentSession().delete(e);

	}

	@Override
	public MacroTache findByID(Long id) {
		// TODO Auto-generated method stub

		Session session = sessionFactory.getCurrentSession();

		return (MacroTache) session.createQuery("FROM MacroTache where id= " + id)
				.list().get(0);
	}

	@Override
	public void update(MacroTache t) {
		// TODO Auto-generated method stub

		getCurrentSession().update(t);
	}

	public List<MacroTache> findAll() {
		// TODO Auto-generated method stub

		return getCurrentSession().createQuery("from MacroTache").list();
	}

	@Override
	public List<MacroTache> getMacoTachesByIds(String[] ids) {
		// TODO Auto-generated method stub
		return getCurrentSession().createQuery("from MacroTache where id in "+prepareIdsForQuery(ids)).list();
	}
	
	// helper methods
	
	private String prepareIdsForQuery(String[] ids){
		String structuredIds ="("+ids[0];
		for(int i=1;i<ids.length-1;i++){
			structuredIds+=" , "+ids[i];
		}
		structuredIds+=" , "+ids[ids.length-1]+" ) ";
		return structuredIds;
	}
	
}
